using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Data;

namespace MonoCash.Data
{
    class XmlBackend : DataBackend
    {
        public override void LoadData()
        {
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(Program.AppSettings.XmlBackendFile);
            DataSet tables = Program.AppSettings.Data.MonoCash;

           
            foreach (DataTable dataTable in tables.Tables )
            {
                XmlNode table = doc.DocumentElement[dataTable.TableName];
                foreach (XmlNode storedRow in table.ChildNodes)
                {
                    DataRow row = dataTable.NewRow();
                    foreach (XmlNode value in storedRow.ChildNodes)
                    {
                        try
                        {
                            if (!dataTable.Columns[value.Name].ReadOnly)
                            {
                                row[value.Name] = Convert.ChangeType(value.InnerText, dataTable.Columns[value.Name].DataType);
                            }
                        }
                        catch
                        {
                            Console.WriteLine("Cannot load some data in file");
                        }
                    }
                    try
                    {
                        dataTable.Rows.Add(row);
                    }
                    catch
                    {
                        Console.WriteLine("Could not load some data from XmlFile");
                    }

                }
                
            }
            Program.AppSettings.Data.IsDataLoaded = true;
        }
        public override void SaveData()
        {
            //There is already an automatic way to do, but it isn't well covered in Mono
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.AppendChild(doc.CreateElement("MonoCash"));
            foreach (System.Data.DataTable table in GetDataTables())
            {
                doc.DocumentElement.AppendChild(doc.CreateElement(table.TableName));
                foreach (System.Data.DataRow row in table.Rows)
                {
                    System.Xml.XmlNode node = doc.CreateElement( table.TableName + "Row");
                    foreach (System.Data.DataColumn column in table.Columns)
                    {
                        if (!column.ReadOnly)
                        {
                            node.AppendChild(doc.CreateElement(column.ColumnName));
                            node[column.ColumnName].InnerText = row[column].ToString();
                        }
                    }
                    doc.DocumentElement[table.TableName].AppendChild(node);
                }
            }
            doc.Save(Program.AppSettings.XmlBackendFile);
        }
    }
}
